package cn.wolfcode.wolf2w.redis.service.impl;


import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.exception.LogicalException;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.util.KeyManager;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
//@Transactional
public class UserRedisServiceImpl implements IUserInfoRedisService {

    @Autowired
    private StringRedisTemplate template;

    @Override
    public void setVerifyCode(String phone,String code) {

        String key = KeyManager.VERIFY_CODE.join(phone);
        //将验证码存入redis,设置5分钟失效时间
        template.opsForValue().set(key, code, KeyManager.VERIFY_CODE.getTime(), TimeUnit.SECONDS);



    }

    @Override
    public String getVerifyCode(String phone) {
        //校验参数phone
        if (phone == null){
            return null;
        }
        //获取redis的key
        String key = KeyManager.VERIFY_CODE.join(phone);
            //获取验证码
            String code = template.opsForValue().get(key);
            return code;

    }

    @Override
    public String setRedis(UserInfo user) {
        //校验参数
        if (user == null){
            throw new LogicalException("参数异常");
        }
        //获取token
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        String key = KeyManager.USER_INFO_TOKEN.join(token);
        //将token和user存入redis,设置30分钟失效时间
        template.opsForValue().set(key,JSON.toJSONString(user), KeyManager.USER_INFO_TOKEN.getTime(), TimeUnit.SECONDS);

        return token;
    }

    @Override
    public UserInfo getRedisUser(String token) {
        //校验token
        if (token == null){
            return null;
        }
        String key = KeyManager.USER_INFO_TOKEN.join(token);
        //获取value
        String user = template.opsForValue().get(key);
        //校验key
        if (template.hasKey(key)){
            //将json格式的user转为UserInfo
            UserInfo userInfo = JSON.parseObject(user,UserInfo.class);

            //重新设置有效时间
            template.expire(key, KeyManager.USER_INFO_TOKEN.getTime(), TimeUnit.SECONDS);
            return userInfo;
        }
        return null;
    }


}
